
angular.module('U9ImHd.utility')
    .factory('Http', ['$q', '$http', 'Config', 'APPCONSTANTS', function ($q, $http, Config, APPCONSTANTS) {
        var o = {};

        o.request = function (cfg) {
            return http(cfg);
        };
        o.get = function (cfg) {
            cfg.method = 'Get';
            return http(cfg);
        };
        o.post = function (cfg) {
            cfg.method = 'POST';
            return http(cfg);
        };

        return o;

        function http (config) {
            var defer = $q.defer();

            if (!config.timeout) {
                config.timeout = APPCONSTANTS.httpTimeOut;
            }
            config.url = getFullURL(config.url);
            config.needOnLine = true;
            $http(config).success(function (result) {
                if (result.Data) {
                    defer.resolve(result.Data);
                } else if (result.status === '0000') {
                    defer.resolve(result.data);
                } else {
                    defer.reject(result.Error || result);
                }
            }).error(function (err) {
                defer.reject(err);
            });

            return defer.promise;
        }

        function getFullURL (url) {
            var address = Config.get('address', APPCONSTANTS.defaultAddress),
                port = Config.get('port', APPCONSTANTS.defaultPort);
            return 'http://' + address + ':' + port + url;
        }
    }]);